﻿using System;
using System.Web;
using _5E.Infrastructure.Logging;
using Newtonsoft.Json;
using StructureMap;
using WholesaleOnline.Controller.Request;
using WholesaleOnline.Controller.Storage;

namespace WholesaleOnline.Controller.Handlers
{
    public class AjaxHandler : IHttpAsyncHandler
    {
        public bool IsReusable { get { return true; } }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            AsyncResult asyncResult = new AsyncResult(cb, context.Response);
            try
            {
                ObjectFactory.GetInstance<IHandlerFactory>().GetHandlers().Handle(ObjectFactory.GetInstance<IWebRequestFactory>().CreateFrom(context));
                asyncResult.SetCompleted();
            }
            catch (Exception)
            {
                asyncResult.SetCompleted();
            }
            return asyncResult;
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            AsyncResult asyncResult = result as AsyncResult;
            HttpResponse response = asyncResult.AsyncState as HttpResponse;

            object exceptionMessage;
            if (HttpStorageFactory.GetStorage().TryGetValue(HttpStorageKeys.Exception, out exceptionMessage))
                LoggingFactory.Logger.Log(exceptionMessage.ToString());

            object value;
            if (HttpStorageFactory.GetStorage().TryGetValue(HttpStorageKeys.Redirect, out value))
                response.Write(JsonConvert.SerializeObject(new { redirect = value.ToString() }));
            else if (HttpStorageFactory.GetStorage().TryGetValue(HttpStorageKeys.Json, out value))
                response.Write(value.ToString());
            response.End();
        }

        public void ProcessRequest(HttpContext context)
        { }
    }
}
